package com.kun.order.service.mq;

import com.alibaba.fastjson2.JSON;
import com.kun.api.IOrderService;
import com.kun.common.constant.ShopCode;
import com.kun.pojo.domain.TradeOrder;
import com.kun.pojo.entity.MQEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@RocketMQMessageListener(topic = "${mq.order.topic}", consumerGroup = "${mq.order.consumer.group}",
        messageModel = MessageModel.BROADCASTING)
public class CancelMQListener implements RocketMQListener<MessageExt> {

    @Autowired
    private IOrderService orderService;

    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            // 1. 解析消息体内容
            MQEntity entity = JSON.parseObject(new String(messageExt.getBody()), MQEntity.class);
            log.info("接收到消息");
            // 2. 将订单状态改成取消
            if (entity.getOrderId() != null) {
                orderService.lambdaUpdate()
                        .set(TradeOrder::getOrderStatus, ShopCode.SHOP_ORDER_CANCEL.getCode())
                        .eq(TradeOrder::getOrderId, entity.getOrderId()).update();
                log.info("订单取消成功");
            }
        } catch (Exception e) {
            log.error("订单取消失败");
        }
    }
}
